import requests
import json
import time

from DrissionPage import Chromium

# 0.创建浏览器连接
browser = Chromium()
tab = browser.latest_tab
# 1.打开网址
tab.get('https://www.faxin.cn/v2/cpgz/list.html')


def get_down(href, max_retries=3):
    for attempt in range(max_retries):
        try:
            tab.get(href)
            item = tab.ele("x://div[@class='container clearfix']/div[@class='content-download']")
            item.click()
            time.sleep(2)
            down_word = tab.ele("x://ul[@class='content-download-type inline']/li[@class='content-download-word']")
            down_word.click()
            return True  # 成功则返回True
        except Exception as e:
            print(f"第{attempt + 1}次尝试失败，正在等待刷新页面重试")
            tab.refresh()
            time.sleep(2)  # 失败后等待2秒再重试
    return False  # 所有尝试都失败则返回False


def get_login():
    try:
        time.sleep(2)
        # 2.点击登录
        tab.ele("x://li[@class='login-c']/a[@class='login']").click()

        # 3. 等待新标签页加载并切换到它
        time.sleep(2)  # 等待新标签页打开

        # 方法1：使用 `get_tab()` 切换到最新标签页
        new_tab = browser.get_tab(1)  # 0=第一个标签页，1=第二个标签页
        # 4.输入账号密码
        new_tab.ele("x://input[@id='user_name']", timeout=2).clear().input('16608526633')
        new_tab.ele("x://input[@id='user_password']").input('Win12356@+')
        # # 5.点击记住操作
        new_tab.ele("x://input[@id='isRemember']").click()
        new_tab.ele("x://input[@id='isAutoLogin']").click()
        # 6.点击登录
        time.sleep(2)
        new_tab.ele("x://input[@id='submitButton']").click()
        time.sleep(5)
        new_tab.close()
        # 7.返回原来页面并刷新
        time.sleep(3)
        tab.refresh()
    except Exception as e:
        tab.refresh()
        time.sleep(3)


headers = {
    "Content-Type": "application/json;charset=UTF-8",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36",

}
cookies = {
    "showUpdate": "2024-12-17",
    "acw_tc": "276aedd817434973108657095e346b036cc18175d44b2e03da2440582e0eb1",
    "faxin_sessionid": "zymvmeubpxwudazggngslhm2",
    "insert_cookie": "37836164",
    "Hm_lvt_a317640b4aeca83b20c90d410335b70f": "1743489515,1743497313",
    "Hm_lpvt_a317640b4aeca83b20c90d410335b70f": "1743497313",
    "HMACCOUNT": "42860E8BCE9827A0"
}
url = "https://www.faxin.cn/v2/api/alyz/search"
failed_list = []

for page in range(1, 4544):
    total_num = 0
    time.sleep(3)
    # 检测页面是否为登录状态
    own = tab.ele("x://li[@class='register']/a", timeout=3)
    if own:
        print('检测到未登录，正在登录……')
        get_login()

    else:
        print('检测到已登录，无需登录')
    data = {
        "searchParams": {},
        "result": [],
        "isAdvSearch": "0",
        "searchType": "1",
        "lib": "0200",
        "sort_field": "",
        "size": 50,
        "page": page
    }
    data = json.dumps(data, separators=(',', ':'))
    response = requests.post(url, headers=headers, cookies=cookies, data=data)
    item_list = response.json()['data']['datas']
    for item in item_list:
        time.sleep(1)
        gid = item['gid']
        href = f'https://www.faxin.cn/v2/cpgz/content.html?gid={gid}'
        if not get_down(href):
            print(f"{gid}下载失败，已尝试3次")
            time.sleep(20)
            print("尝试最终请求……")
            try:
                get_login()
            except:
                failed_list.append(gid)
        # 计算总条数
        total_num += 1
    print(f"第{page}页下载完成,有{total_num}条已下载完成……")

print(failed_list, '==>查收未成功下载数据的gid列表')
